<template>
    <div class="list-items">
        <template v-if="loading">
            <div v-for="n in 6" :key="n" class="loading-item" data-testid="loading" id="loading">
                <span class="glow-checkbox" />
                <span class="glow-text">
                    <span>Loading</span> <span>cool</span> <span>state</span>
                </span>
            </div>
        </template>
        <div v-else-if="isEmpty" class="list-items" data-testid="empty" id="empty">
            <div class="wrapper-message">
                <span class="icon-check" />
                <p class="title-message">You have no tasks</p>
                <p class="subtitle-message">Sit back and relax</p>
            </div>
        </div>
        <template v-else>
            <Task v-for="task in tasksInOrder" :key="task.id" :task="task" @archive-task="onArchiveTask"
                @pin-task="onPinTask" />
        </template>
    </div>
</template>

<script lang="ts" setup>
import Task from '../Task/index.vue';
import type { TaskData } from '@/types/task';
import { computed } from 'vue';

type PureTaskListProps = {
    /** List of tasks */
    tasks: TaskData[]
    /** Loading state */
    loading?: boolean
    /** Event to change the task to archived */
    onArchiveTask: (id: string) => void
    /** Event to change the task to pinned */
    onPinTask: (id: string) => void
}

const props = defineProps<PureTaskListProps>();

const isEmpty = computed(() => props.tasks.length === 0)

const tasksInOrder = computed(() => {
    return [
        ...props.tasks.filter(t => t.state === 'TASK_PINNED'),
        ...props.tasks.filter(t => t.state !== 'TASK_PINNED'),
    ]
})

const emit = defineEmits<{
  (e: 'archive-task', id: string): void
  (e: 'pin-task', id: string): void
}>();

/**
 * Event handler for archiving tasks
 */
function onArchiveTask(task: TaskData): void {
    emit('archive-task', task);
}
/**
 * Event handler for pinning tasks
 */
function onPinTask(task: TaskData): void {
    emit('pin-task', task);
}
</script>
